package zld369504.tw.m_team.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import zld369504.tw.m_team.DataParser;
import zld369504.tw.m_team.exception.MyException;
import zld369504.tw.m_team.OnRecyclerViewItemClickListener;
import zld369504.tw.m_team.R;
import zld369504.tw.m_team.TorrentDetailActivity;
import zld369504.tw.m_team.TorrentListRecyclerViewAdapter;
import zld369504.tw.m_team.api.MTeamHttpsApi;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.dao.Torrent;

public class TorrentListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OnRecyclerViewItemClickListener {

    public static final String adult = "AdultFragment";
    public static final String comprehensive = "ComprehensiveFragment";
    public static final String fourK = "FourKFragment";
    private View rootView;
    private SwipeRefreshLayout refreshLayout;
    private TorrentListRecyclerViewAdapter adapter;
    private int index;

    public static TorrentListFragment getInstance(int index) {
        TorrentListFragment fragment = new TorrentListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            index = bundle.getInt("index", 0);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_torrent_list, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        RecyclerView adultMovieListView = rootView.findViewById(R.id.torrentListView);

        adapter = new TorrentListRecyclerViewAdapter(getActivity());
        adapter.setOnItemClickListener(this);
        adultMovieListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adultMovieListView.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(this);
        requestForTorrentList();
    }

    @Override
    public void onRefresh() {
        requestForTorrentList();
    }

    protected void requestForTorrentList() {
        refreshLayout.setRefreshing(true);
        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(final FlowableEmitter<String> emitter) throws Exception {
                final MTeamHttpsApi api = MTeamHttpsApiImpl.getInstance();
                final Callback callback = new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        emitter.onError(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        int responseCode = response.code();
                        if (responseCode == 200) {
                            String body = response.body().string();
                            emitter.onNext(body);
                            emitter.onComplete();
                        } else if (responseCode == 302) {
                            String location=response.header("Location");
                            if(!TextUtils.isEmpty(location) && location.contains("verify.php")){
                                Response realResponse=api.verify(location);
                                if(realResponse!=null){
                                    if (realResponse.code() == 200) {
                                        String body = realResponse.body().string();
                                        emitter.onNext(body);
                                        emitter.onComplete();
                                    } else {
                                        emitter.onError(new MyException(
                                                "Expect response code is 200 after verify the first real request,but " + responseCode + " return.",""
                                        ));
                                    }
                                } else {
                                    //验证网页返回不是302code
                                    emitter.onError(new MyException(
                                            "Expect response code is 302 after verify,but " + responseCode + " return.",""
                                    ));
                                }
                            } else {
                                emitter.onError(new MyException(
                                        "Expect response code is 200,but " + responseCode + " return.",location
                                        ));
                            }
                        } else {
                            emitter.onError(new MyException(
                                    "Expect response code is 200,but " + responseCode + " return.",""
                            ));
                        }
                    }
                };
                switch (index) {
                    case 1:
                        api.getComprehensiveTorrentsList(callback);//综合列表
                        break;
                    case 2:
                        api.getFourKList(callback);//4k
                        break;
                    case 3:
                        api.getGeneralAdultMovieList(callback);//成人列表
                        break;
                    case 10:
                        api.getBookmarksTorrentList(0, callback);//综合收藏
                        break;
                    case 11:
                        api.getBookmarksTorrentList(1, callback);//电影收藏
                        break;
                    case 12:
                        api.getBookmarksTorrentList(2, callback);//成人收藏
                        break;
                    default:
                        emitter.onComplete();
                        break;
                }
            }
        }, BackpressureStrategy.DROP)
                .map(new Function<String, List<Torrent>>() {
                    @Override
                    public List<Torrent> apply(String body) throws Exception {
                        return DataParser.parseTorrentList(body);
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<Torrent>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(List<Torrent> torrents) {
                        adapter.setList(torrents);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable t) {
                        refreshLayout.setRefreshing(false);
                        if (t instanceof MyException) {
                            String location = ((MyException) t).getLocation();
                            showErrorDialog(location);
                        } else {
                            showErrorDialog("请求出错:" + t.toString());
                        }
                    }

                    @Override
                    public void onComplete() {
                        refreshLayout.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), TorrentDetailActivity.class);
        Torrent torrent = adapter.getItem(position);
        Bundle bundle = new Bundle();
        bundle.putSerializable("torrent", torrent);
        intent.putExtras(bundle);
        if (index == 3 || index == 12) {
            intent.putExtra("isAdult", true);
        } else {
            intent.putExtra("isAdult", false);
        }
        startActivity(intent);
    }
}
